<script lang="ts" setup>
import type { FormInstance } from '@arco-design/web-vue'
import { Message } from '@arco-design/web-vue'
import { OrderApi } from '@/apis'
import { useForm } from '@/hooks'

const emit = defineEmits(['success'])

const visible = ref<boolean>(false)
const formRef = ref<FormInstance>()

const { form, resetForm } = useForm<OrderApi.OrderPayTypeUpdateReq>({
  orderId: undefined,
  finAccountId: undefined,
  payTime: undefined,
})

const rules: FormInstance['rules'] = {
  payTime: [{ required: true, message: '请选择支付时间' }],
  finAccountId: [{ required: true, message: '请选择财务账户' }],
}

const handleOk = async () => {
  emit('success')
}

const handleCancel = () => {
  visible.value = false
}

const beforeOk = async () => {
  const isInvalid = await formRef.value?.validate()
  if (isInvalid) {
    return false
  }
  try {
    await OrderApi.updatePayType(form)
    Message.success('操作成功')
    return true
  // eslint-disable-next-line unused-imports/no-unused-vars
  } catch (_) {
    return false
  }
}

const reset = () => {
  formRef.value?.resetFields()
  resetForm()
}

const open = (data: OrderApi.OrderResp) => {
  reset()
  form.orderId = data.id
  form.finAccountId = data.finAccountId
  form.payTime = data.payTime
  visible.value = true
}

defineExpose({
  open,
})
</script>

<template>
  <a-modal v-model:visible="visible" width="520px" title="修改支付方式" @before-ok="beforeOk" @ok="handleOk" @cancel="handleCancel">
    <a-form ref="formRef" :model="form" :rules="rules" layout="vertical">
      <a-form-item label="财务账户" field="finAccountId">
        <AccountSelect v-model="form.finAccountId" class="flex-1" placeholder="财务账户(输入关键字搜索)" :exclude-online="true" />
      </a-form-item>
      <a-form-item label="支付时间" field="payTime">
        <a-date-picker
          v-model="form.payTime"
          style="width: 220px; margin: 0 24px 24px 0;"
          show-time
          :time-picker-props="{ defaultValue: '00:00:00' }"
          format="YYYY-MM-DD HH:mm:ss"
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<style lang='less' scoped>
</style>
